//
//  AllViewController.m
//  FKGW
//
//  Created by song ce on 2017/2/17.
//  Copyright © 2017年 song ce. All rights reserved.
//

#import "AllViewController.h"
#import "NearShopCell.h"
#import "StoreViewController.h"
#import "MJRefresh.h"
#define KpageCount   @"10"    //每页数据量
@interface AllViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,assign)NSInteger arrCount;//用于判断上拉加载更多是否有
@property(nonatomic,strong)NSMutableDictionary *dataDic;
@property(nonatomic,assign)BOOL isNeedReloadData;

@end

@implementation AllViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataDic = [NSMutableDictionary dictionary];
    //表示图
    [self tableViewAndHeaderView];
//    //加载更多数据
//    [self loadMoreData];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reload_data) name:@"reLoadDataWhenLocationChanged" object:nil];
 }

-(void)reload_data{
    self.isNeedReloadData = YES;
    [self loadData];
}

//h文件有声明，在外部文件调用
-(void)loadData{
    NSString *key = [NSString stringWithFormat:@"%d",self.vcIndex];
    self.dataSource = self.dataDic[key];
    if(self.dataSource.count){
        [self.tableV reloadData];
    }else{
        //数据源
        self.dataSource = [NSMutableArray array];
        [self loadDataWithIndex:0 withPage:@"1"];
    }
    DLog(@"加载数据----%d",self.vcIndex);
}
#pragma mark - 加载更多数据
- (void)loadMoreData{
    __weak typeof(self) weakSelf = self;
    self.index = 1;
    //上拉加载更多
    self.tableV.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        if(weakSelf.arrCount<[KpageCount intValue]){
            [weakSelf.tableV.mj_footer setState:MJRefreshStateNoMoreData];
        }else{
            self.index ++;
            NSString *page = [NSString stringWithFormat:@"%d",self.index];
            //参数2 代表操作的是上拉加载更多
            [weakSelf loadDataWithIndex:2 withPage:page];
        }
    }];
    
    //下拉刷新
    self.tableV.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.index = 1;
        [weakSelf loadDataWithIndex:1 withPage:@"1"];
    }];
}
-(void)showTips{
    [MBProgressHUD showTipMessageInWindow:@"没有您的位置信息\r\n无法为您查询相关数据\r\n请到设置中修改定位权限"];
}

//加载数据
- (void)loadDataWithIndex:(int)index withPage:(NSString*)page{
    if(!LONGITUDE.length){
        [self.view addSubview:self.noDataIUmageV];
         [self performSelector:@selector(showTips) withObject:nil afterDelay:1];
        return;
    }
    [self.noDataIUmageV removeFromSuperview];
    //2.60 附近接口--行业
    NSString *uid ;
    if(USERID.length){
        uid= USERID;
    }else{
        uid= @"";
    }
    NSString *which = [NSString stringWithFormat:@"%d",self.vcIndex];
    NSDictionary *paraDic = @{
                              @"userId":uid,
                              @"which":@"1",
                              @"lon":LONGITUDE,
                              @"lat":LATITUDE,
                              @"currentPage":page,
                              @"size":KpageCount,
                              @"industryId":self.industryId
                              };
    if(index==0&&self.vcIndex!=0&&!self.isNeedReloadData){//第一次请求数据 使用这个进度条
           [MBProgressHUD showLoadingGif];
    }
    self.isNeedReloadData = NO;
    __weak typeof(self)  weakSelf = self;
    [Tools AFNetworkingRequestTypePostWithUrl:MYNEARBY paramters:paraDic  afterResultBlock:^(NSDictionary *resultDic) {
        DLog(@"near-行业--index--%@--%@",which,resultDic);
        if([resultDic[@"flag"] isEqualToString:@"true"]){
            NSArray *dataArr = resultDic[@"data"];
            if([dataArr isKindOfClass:[NSNull class]]){
                if(index==0){
                    [MBProgressHUD dismissHUD];
                }
                if([weakSelf.tableV.mj_header isRefreshing]){
                    [weakSelf.tableV.mj_header endRefreshing];
                }
                if([weakSelf.tableV.mj_footer isRefreshing]){
                    [weakSelf.tableV.mj_footer endRefreshing];
                }
                return ;
            }
            NSMutableArray *startEndArr = [NSMutableArray array];
            for(NSDictionary *dic in dataArr){
                NearShopModel *model = [NearShopModel  modelWithDic:dic];
                [startEndArr addObject:model];
            }
            if(index==1&&weakSelf.dataSource.count>0){
                [weakSelf.dataSource removeAllObjects];
            }
            [weakSelf.dataSource addObjectsFromArray:startEndArr];
            if(!weakSelf.dataSource.count){
                [weakSelf.view addSubview:weakSelf.noDataIUmageV];
            }else{
                [weakSelf.noDataIUmageV removeFromSuperview];
                [weakSelf.dataDic setObject:weakSelf.dataSource forKey:which];
            }
            weakSelf.arrCount = startEndArr.count;
            [weakSelf.tableV reloadData];
            if(weakSelf.dataSource.count){
                weakSelf.tableV.hidden = NO;
            }
            if(index==0){
                if(startEndArr.count==[KpageCount integerValue]){
                    //加载更多数据
                    [self loadMoreData];
                }else{
                    weakSelf.tableV.mj_header = nil;
                    weakSelf.tableV.mj_footer = nil;
                }
                [MBProgressHUD dismissHUD];
            }
            if([weakSelf.tableV.mj_header isRefreshing]){
                [weakSelf.tableV.mj_header endRefreshing];
            }
            if([weakSelf.tableV.mj_footer isRefreshing]){
                [weakSelf.tableV.mj_footer endRefreshing];
            }
            if(weakSelf.arrCount<[KpageCount intValue]){
                [weakSelf.tableV.mj_footer setState:MJRefreshStateNoMoreData];
            }
        }else{
            [MBProgressHUD dismissHUD];
            if(resultDic[@"errorString"]){
                [MBProgressHUD showTipMessageInWindow:resultDic[@"errorString"]];
            }
        }
    }];
}

- (void)tableViewAndHeaderView{
    //表视图
    self.tableV = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, Main_Screen_Width, Main_Screen_Height-49-kNaviBarHeight-44-40) style:UITableViewStylePlain];
    self.tableV .showsVerticalScrollIndicator = NO;
    self.tableV .backgroundColor = DEF_COLOR242;
    self.tableV .delegate = self;
    self.tableV .dataSource =self;
    [self.view addSubview:self.tableV ];
    self.tableV .tableFooterView = [[UIView alloc]init];
    self.tableV.hidden = YES;
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *ident=@"acqtell";
    NearShopCell *cell=[tableView dequeueReusableCellWithIdentifier:ident];
    if(cell==nil){
        cell=[[[NSBundle mainBundle]loadNibNamed:@"NearShopCell" owner:self options:nil]lastObject];
    }
    cell.isLive = YES;
    cell.isShowRightBottonButn = YES;
    cell.model = self.dataSource[indexPath.row];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 200;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NearShopModel *model = self.dataSource[indexPath.row];
    StoreViewController *goodsDetail  = [[StoreViewController alloc]init];
    goodsDetail.storeId = model.id;
    goodsDetail.vcName = model.name;
    goodsDetail.hidesBottomBarWhenPushed = YES;
    [[self baseNavigationViewController]  pushViewController:goodsDetail animated:YES];
}

- (BaseNavigationViewController*)baseNavigationViewController{
    UIResponder *next = self.nextResponder;
    while (next!=nil) {
        if([next isKindOfClass:[BaseNavigationViewController class]]){
            return (BaseNavigationViewController*)next;
        }
        next = next.nextResponder;
    }
    return nil;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
